$(document).ready(function() {
    SB.friendlyTime();
    SB.resetFollowBtn = function($this, followed) {
        if (followed) {
            $this.addClass('btn-success');
            $this.find('i').addClass('icon-white');
        } else {
            $this.removeClass('btn-success');
            $this.find('i').removeClass('icon-white');
        }
    };

    // Change color when user follow board
    $(document).on('click', '.follow-board', function() {
        var boardId = $(this).attr("data-board-id");
        var params = {};
        params.board_id = boardId;
        var $this = $(this);
        $.post("/api/board/follow/", params, function(data) {
            data = JSON.parse(data);
            $this.find('.board-followers-count').text(data.followers_count);
            SB.resetFollowBtn($this, _.contains(data.followers, SB.user.id));
        });
    });

    SB.resetAllFollowBtns = function() {
        SB.userBoardsArray = [];
        if (SB.userBoards) {
            $.each(SB.userBoards, function(index, item) {
                SB.userBoardsArray.push(parseInt(item.id));
            });
        }

        $('.follow-board').each(function(index, el) {
            var $el = $(el);
            SB.resetFollowBtn($el, _.indexOf(SB.userBoardsArray, parseInt($el.attr("data-board-id"))) != -1);
        });
    };
    
    SB.resetAllFollowBtns();

    // Setup ScrollMore
    ScrollMore.opts.nextUrl = $('a#next').attr('href');
    var before = function() {
        SB.showLoading();
    };
    var success = function(data) {
        SB.hideLoading();
        SB.friendlyTime();
        SB.resetAllFollowBtns();
        console.log(data);
        data = JSON.parse(data);

        // Append to current content
        $('.articles').append(data.html);
        if (data.cursor) {
            ScrollMore.opts.nextUrl = "/api/board/cursor/?curs=" + encodeURIComponent(data.cursor);
        } else {
            ScrollMore.opts.nextUrl = "";
        }
    };
    var error = function() {
        SB.hideLoading();
    };
    ScrollMore.init(before, success, error);
});
